<style lang="less" scoped>
    @import '../../styles/common.less';
    @import '../../styles/loading.less';
    @import 'chapter.less';
</style>

<template>
    <div>
        <Row style="font-size: 15px;">
            <Col span="22">
            章名称：<Input v-model="queryCon.name" clearable style="width: 15%"></Input>
            <span @click="loadList"><Button type="primary" icon="android-search">查询</Button></span>
            </Col>
            <Col span="2">
            <span @click="showAdd"><Button type="primary" icon="android-add">新增</Button></span>
            </Col>
        </Row>
        <div class="main-table">
            <Table border :columns="columns" :data="data"></Table>
        </div>
        <div class="pagination">
            <Page :total="total" size="small" :page-size="pageSize" :current.sync="pageIndex" @on-change="loadList" show-total show-elevator></Page>
        </div>
        <Modal
                v-model="viewModalVisible"
                title="章信息"
                @on-ok="viewModalVisible = false"
                @on-cancel="viewModalVisible = false"
                width="40%">
            <Form :model="formData" :label-width="90">
                <Row>
                    <Col span="18">
                    <FormItem label="章名称">
                        <div class="conts">{{formData.name}}</div>
                    </FormItem>
                    </Col>
                </Row>
                <Row >
                    <Col span="18">
                    <FormItem label="机构名称">
                        <div class="conts">{{formData.organizename}}</div>
                    </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="18">
                    <FormItem label="创建时间">
                        <div class="conts">{{formData.createTime}}</div>
                    </FormItem>
                    </Col>
                </Row>
                <FormItem label="图片">
                    <div class="admin-upload-list" :key="formData.imgUrl">
                        <Modal v-model="showImgDetail" title="查看图片" @on-cancel="showImgDetail = false">
                            <img :src="formData.imgUrl" width="100%" height="100%">
                            <div slot="footer">
                                <Button type="primary" @click="showImgDetail = false">确定</Button>
                            </div>
                        </Modal>
                        <template>
                            <img :src="formData.imgUrl">
                            <div class="admin-upload-list-cover">
                                <Icon type="ios-eye-outline" @click.native="showImgDetail = true"></Icon>
                            </div>
                        </template>
                    </div>
                </FormItem>
            </Form>
        </Modal>
        <Modal v-model="saveModalVisible"
               :title="(formData.id ? '修改' : '新增') + '章信息'"
               width="40%"
               @on-cancel="saveModalVisible = false"
               :mask-closable="false">
            <Form :model="formData" :label-width="125">
                <Row>
                    <Col span="18">
                    <FormItem label="章名称">
                        <Input v-model="formData.name" clearable ></Input>
                    </FormItem>
                    </Col>
                </Row>
                <Row v-if="orgShow">
                    <Col span="18">
                    <FormItem label="机构名称">
                        <Select v-model="formData.orgId" filterable clearable>
                            <Option v-for="item in organizeList" :value="item.id" :key="item.id">{{ item.orgName }}</Option>
                        </Select>
                    </FormItem>
                    </Col>
                </Row>
                <FormItem label="图片">
                    <div class="admin-upload-list" v-for="item in uploadList" :key="item.url">
                        <Modal v-model="showImg" title="查看图片" @on-cancel="showImg = false">
                            <img :src="item.url" width="100%" height="100%">
                            <div slot="footer">
                                <Button type="primary" @click="showImg = false">确定</Button>
                            </div>
                        </Modal>
                        <template v-if="item.status === 'finished'">
                            <img :src="item.url">
                            <div class="admin-upload-list-cover">
                                <Icon type="ios-eye-outline" @click.native="showImg = true"></Icon>
                                <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                            </div>
                        </template>
                        <template v-else>
                            <Spin fix v-if="item.showProgress">
                                <Icon type="load-c" size=18 class="demo-spin-icon-load"></Icon>
                            </Spin>
                        </template>
                    </div>
                    <Upload
                            ref="upload"
                            name="file"
                            :action="SERVER_HOST + 'upload/uploadFile'"
                            :format="['jpg', 'png', 'jpeg', 'gif', 'bmp', 'svg']"
                            :max-size="2048"
                            :on-exceeded-size="handleMaxSize"
                            :on-format-error="handleFormatError"
                            :on-success="handleSuccess"
                            :before-upload="handleBeforeUpload"
                            type="drag"
                            multiple
                            :show-upload-list="false"
                            style="display: inline-block;width:58px;"
                    >
                        <div style="width: 58px;height:58px;line-height: 58px;">
                            <Icon type="camera" size="20"></Icon>
                        </div>
                    </Upload>
                </FormItem>
            </Form>

            <div slot="footer">
                <Button type="primary" @click="activitySave" :disabled="pictureDis">保存</Button>
                <Button type="ghost" style="margin-left: 8px" @click="saveModalVisible = false">取消</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    import util from '@/libs/util';
    import CONSTANTS from '@/config/constants';
    import Cookies from 'js-cookie';
    import getDate from '@/util/getDate.js';

    export default {
        name: 'exportable-table',
        data () {
            return {
                columns: [{
                    title: '序号',
                    key: 'rownum',
                    width: 60,
                    align: 'center',
                    render: (h, params) => {
                        return h('div', {}, ((this.pageIndex - 1) * this.pageSize + params.index + 1));
                    }
                }, {
                    title: '章名称',
                    key: 'name'
                }, {
                    title: '缩略图',
                    key: 'imgmin',
                    render: (h, params) => {
                        let imgpath = this.SERVER_HOST + params.row.cover;
                        return h('img', {
                            style: {
                                height: '60px'
                            },
                            attrs: {
                                src: imgpath
                            },
                            on: {
                                click: () => {
                                    this.formData.imgUrl = imgpath;
                                    this.showImgDetail = true;
                                }
                            }
                        });
                    }
                }, {
                    title: '机构名称',
                    key: 'organizename'
                }, {
                    title: '创建时间',
                    key: 'createTime'
                }, {
                    title: '操作',
                    key: 'action',
                    width: 300,
                    align: 'center',
                    render: (h, params) => {
                        let isShow = 'none';
                        if (params.row.releases == 'NO') {
                            isShow = 'inline';
                        }  return h('div', [
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.detail(params.row);
                                    }
                                }
                            }, '详情'),
                            h('Button', {
                                props: {
                                    type: 'primary',
                                    size: 'small'
                                },
                                style: {
                                    marginRight: '5px'
                                },
                                on: {
                                    click: () => {
                                        this.showEdit(params.row);
                                    }
                                }
                            }, '修改'),
                            h('Button', {
                                props: {
                                    type: 'error',
                                    size: 'small'
                                },
                                on: {
                                    click: () => {
                                        this.delete(params.row.id);
                                    }
                                }
                            }, '删除')
                        ]);
                    }
                }],
                data: [],
                formData: {},
                viewModalVisible: false,
                saveModalVisible: false,
                priceModalVisible: false,
                showImgDetail: false,
                showImg: false,

                total: 0,
                pageIndex: 1,
                pageSize: 8,
                queryCon: {
                    createTime: '',
                    name: '',
                    organize: ''
                },
                organizeList: [],
                id: '',
                uploadList: [],
                imgUrl: '',
                SERVER_HOST: CONSTANTS.SERVER_HOST,
                orgShow: false,
                pictureDis: false
            };
        },
        mounted () {
            this.loadList();
        },
        methods: {
            loadList () {
                let baseuser = eval('(' + Cookies.get('baseUser') + ')');
                util.ajax.post('/busine/chapter/list', util.toFormData({
                    page: this.pageIndex,
                    size: this.pageSize,
                    name: this.queryCon.name,
                    organizeid: baseuser.orgId
                })).then(res => {
                    var lists = res.data.data.pageInfo.list;
                    for (var i = 0; i < lists.length; i++) {
                        if (lists[i].organize) {
                            lists[i]['organizename'] = lists[i].organize.orgName;
                        }
                        lists[i]['createTime'] = getDate.getDate(lists[i].createTime, 'time');
                    }
                    this.organizeList = res.data.data.organizeList;
                    this.data = res.data.data.pageInfo.list;
                    this.total = res.data.data.pageInfo.total;
                });
            },
            detail (obj) {
                let _this = this;
                util.ajax.post('/busine/chapter/detail', util.toFormData({
                    id: obj.id
                })).then(res => {
                    if (res.data.data) {
                        var li = res.data.data;
                        if (li.organize) {
                            li ["organizename"] = obj.organize.orgName;
                        }
                        li['createTime'] = getDate.getDate(li.createTime, 'time');
                        li['imgUrl'] = CONSTANTS.SERVER_HOST + li.cover;
                        _this.formData = res.data.data;
                        _this.viewModalVisible = true;
                    } else {
                        _this.$Modal.error({
                            title: '警告',
                            content: '出错了'
                        });
                    }
                });
            },
            showAdd (obj) {
                this.orgShow = false;
                this.formData = {};
                this.formData['orgId'] = eval('(' + Cookies.get('baseUser') + ')').orgId;
                if (eval('(' + Cookies.get('baseUser') + ')').orgId === 0) this.orgShow = true;
                this.saveModalVisible = true;
                this.uploadList = this.$refs.upload.fileList = [];
            },
            showEdit (obj) {
                this.orgShow = false;
                this.formData = {};
                if (eval('(' + Cookies.get('baseUser') + ')').orgId === 0) this.orgShow = true;
                util.ajax.post('/busine/chapter/detail', util.toFormData({
                    id: obj.id
                })).then(res => {
                    if (res.data.data) {
                        var li = res.data.data;
                        if (li.organize) {
                            li["orgId"] = li.organize.id;
                        }
                        li['createTime'] = getDate.getDate(li.createTime, 'time');
                        var li = res.data.data;
                        this.imgUrl = li.cover;
                        if (li.cover) {
                            this.$refs.upload.fileList = [];
                            this.uploadList = [{
                                status: 'finished',
                                showProgress: true,
                                url: CONSTANTS.SERVER_HOST + li.cover
                            }];
                            this.imgUrl = CONSTANTS.SERVER_HOST + li.cover;
                        } else {
                            this.uploadList = this.$refs.upload.fileList = [];
                        }

                        this.formData = res.data.data;
                        this.saveModalVisible = true;
                    } else {
                        this.$Modal.error({
                            title: '警告',
                            content: '出错了'
                        });
                    }
                });
            },
            activitySave () {
                let formData = {};
                for (let key in this.formData) {
                    formData[key] = this.formData[key];
                }
                let baseuser = eval('(' + Cookies.get('baseUser') + ')');
                if (baseuser.type === 2) {
                    formData['orgId'] = baseuser.orgId;
                };
                util.ajax.post('/busine/chapter/save', util.toFormData(formData)).then(res => {
                    if (res.data.message === 'SUCCESS') {
                        this.saveModalVisible = false;
                        this.$Message.success('保存成功！');
                        this.pageIndex = 1;
                        this.loadList();
                    } else {
                        this.$Message.warning(res.data.message || '未知错误！');
                    }
                });
            },
            delete (id) {
                this.$Modal.confirm({
                    title: '提示',
                    content: '<p>确定删除？</p>',
                    onOk: () => {
                        util.ajax.post('/busine/chapter/delete', util.toFormData({
                            id: id
                        })).then(res => {
                            if (res.data.message === 'SUCCESS') {
                                this.$Message.success('删除成功！');
                                this.loadList();
                            }
                        });
                    },
                    onCancel: () => {
                    }
                });
            },
            handleSuccess (res, file) {
                this.uploadList = [{
                    showProgress: true
                }]
                var xmlhttp = null;
                var urlPath = CONSTANTS.SERVER_HOST + res.data.imgUrl;
                if (window.ActiveXObject) {
                    xmlhttp = new ActiveXObject("Microsoft.XMLDOM");
                } else {
                    if (window.XMLHttpRequest) {
                        xmlhttp = new XMLHttpRequest();
                    }
                }
                let interval = setInterval(() => {
                    xmlhttp.open('GET', urlPath, false);
                    xmlhttp.send();
                    if ((xmlhttp.readyState === 4 && xmlhttp.status === 200)) {
                        clearInterval(interval);
                        this.$Notice.success({
                            title: '文件上传成功',
                            desc: '文件 ' + file.name + ' 上传成功。',
                            duration: 2
                        });
                        file.url = CONSTANTS.SERVER_HOST + res.data.imgUrl;
                        file.name = res.data.fileName;
                        this.uploadList = this.$refs.upload.fileList;
                        this.formData.cover = res.data.imgUrl;
                        this.imgUrl = res.data.imgUrl;
                        this.pictureDis = false;
                    }
                }, 500);
            },
            handleFormatError (file) {
                this.$Notice.warning({
                    title: '文件格式不正确',
                    desc: '文件 ' + file.name + ' 格式不正确，请选择图片文件。',
                    duration: 5
                });
                this.pictureDis = false;
            },
            handleMaxSize (file) {
                this.$Notice.warning({
                    title: '超出文件大小限制',
                    desc: '文件 ' + file.name + ' 太大，不能超过 2M。',
                    duration: 5
                });
                this.pictureDis = false;
            },
            handleRemove (file) {
                this.uploadList = [];
                this.$refs.upload.fileList = [];
                this.formData.cover = '';
            },
            handleBeforeUpload () {
                const check = this.uploadList.length < 1;
                if (!check) {
                    this.$Notice.warning({
                        title: '最多只能上传 1 张图片。',
                        duration: 5
                    });
                }
                this.pictureDis = true;
                return check;
            },
            refresh () {
                this.queryCon = {
                    createTime: '',
                    name: '',
                    id: '',
                    organize: ''

                };
                this.loadList();
            }
        }
    };
</script>
